import eventBus from "./eventBus";
import socket from "./socket";
import androidMsg from "./androidMessage";
import axios from "axios";
import vue from "Vue";
class serverMessage {
  constructor() {
    eventBus.$on("get_music_list", this.get_music_list.bind(this));
    eventBus.$on("request_file", this.request_file);
    eventBus.$on("fileUrl", this.fileUrl.bind(this));
  }
  private get_music_list(msg: any) {
    console.log("back_music_list:", msg);
    router.push({ name: "musicList", params: { username: msg.from } });
    socket.sendMsg("message", {
      type: "back_music_list",
      data: {
        to: msg.from,
        list: androidMsg.music_lists
      }
    });
  }

  private fileUrl(msg: any) {
    console.log("recive fiel URL data:", msg.url);
    this.downloader(msg.url);
  }

  private downloader(url: String) {
    return;
    var adownLoda = document.createElement("a");
    adownLoda.href = url;
    adownLoda.download = url;
    document.body.appendChild(adownLoda);
    adownLoda.click();
  }

  private downloader_(url: String) {
    /*
    var adownLoda = document.createElement("a");
    adownLoda.href = url;
    adownLoda.download = url;
    document.body.appendChild(adownLoda);
    adownLoda.click();
    */
    let self = this;
    axios.get(url, { responseType: "blob" }).then(res => {
      let blob = res.data;
      let url = URL.createObjectURL(blob);
      self.download(url);
      // 用完释放URL对象
      URL.revokeObjectURL(url);
    });
  }

  private request_file(msg: any) {
    console.log("msg:", msg);
    eventBus.$emit("uploadFile", {
      name: msg.name
    });
    setTimeout(function() {
      androidMsg.send_msg({
        type: "request_music",
        to: msg.from,
        path: msg.path
      });
    }, 500);
    /*
    
    */
  }
}

export default new serverMessage();
